package com.hop.thread.safe;

public class Account {
	
	//账户名
	private String accountName;
	
	//余额
	private double balance;
	
	//表明账户是否有存款
	private boolean flag = false;
	
	public Account(){}
	
	public Account(String accountName,double balance){
		this.accountName = accountName;
		this.balance = balance;
	}
	
	public String getAccountName() {
		return accountName;
	}
	public void setAccountName(String accountName) {
		this.accountName = accountName;
	}
	public double getBalance() {
		return balance;
	}
	public void setBalance(double balance) {
		this.balance = balance;
	}
	
	
	/**
	 * 存钱
	 */
	public synchronized void deposite(double depositeAmount, int i){
		if(flag){
			//账户中有余额，此时当前线程需要等待
			try {
				System.out.println(Thread.currentThread().getName() + " 开始要执行wait操作" + " -- i=" + i);
				wait();
				System.out.println(Thread.currentThread().getName() + " 执行了wait操作" + " -- i=" + i);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			 //开始存钱
			 System.out.println(Thread.currentThread().getName() + " 存款:" + depositeAmount + " -- i=" + i);
			 setBalance(balance+depositeAmount);
			 flag = true;
			 //唤醒其他线程
			 notifyAll();
			 
			 try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + "-- 存钱 -- 执行完毕" + " -- i=" + i);
		}
	}
	
	public synchronized void draw(double drawAmount,int j){
		if(!flag){
			 try {
				 // 账户中还没人存钱进去，此时当前线程需要等待阻塞
				 System.out.println(Thread.currentThread().getName() + " 开始要执行wait操作" + " 执行了wait操作" + " -- j=" + j);
				 wait();
				 System.out.println(Thread.currentThread().getName() + " 执行了wait操作" + " 执行了wait操作" + " -- j=" + j);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			//开始取钱
			System.out.println(Thread.currentThread().getName() + " 取钱：" + drawAmount + " -- i=" + j);
			setBalance(getBalance() - drawAmount);
			flag = false;
			notifyAll();
			System.out.println(Thread.currentThread().getName() + "-- 取钱 -- 执行完毕" + " -- i=" + j); 
		}
	}
	
}
